#include "home.h"
#include "recordbooks.h"
#include "ui_recordbooks.h"

#include <QFile>
#include <QStandardItemModel>
#include <QStringListModel>
#include <QTextCodec>
RecordBooks::RecordBooks(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RecordBooks)
{
    ui->setupUi(this);
    initWindow();
}

RecordBooks::~RecordBooks()
{
    delete ui;
}
void RecordBooks::initWindow(){
    this->setLayout(ui->mainLayout);
    this->setFixedSize(600,800);
    //this->setWindowFlags(Qt::FramelessWindowHint); // 设置窗口无边框
    this->setWindowTitle("");
    borroweredBookFilePath="borrowbooks.txt";
    returnedBookFilePath="HistoryBooks.txt";

    ui->frame->resize(this->width(),this->height()*1.0/8);
    ui->returnButton->resize(ui->frame->width()*1.0/5,ui->frame->height());
    ui->label->resize(ui->frame->width(),ui->frame->height());

    initBooks();

    setDataTotreeView();

    QFont font;
    font.setPointSize(12);//设置字号为12
    ui->treeView->setFont(font);
    ui->treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);


    connect(ui->returnButton,&QPushButton::clicked,this,[this](){
        this->close();
        home*h=new home();
        h->show();
    });
}
void RecordBooks::initBooks(){
    historyBooks.clear();
    QTextCodec* codec = QTextCodec::codecForName("UTF-8");
    QFile file1(borroweredBookFilePath);
    if (file1.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file1);
        in.setCodec(codec);
        while (!in.atEnd()) {
            QString line = in.readLine();
            qDebug() << "未归还数据：" << line;
            line=line.replace(" ","");
            QStringList dataList = line.split("/");
            if (dataList.size() < 9) {
                qWarning() << "数据格式错误：" << line;
                continue;
            }

            QString name = dataList[0];
            QString publisher = dataList[1];
            QString author = dataList[2];
            QString ISBN = dataList[3];
            QString categroy = dataList[4];
            QString collectionLocation = dataList[5];
            int currentCollection = dataList[6].toInt();
            int allCollection = dataList[7].toInt();
            QDate loanTime = QDate::fromString(dataList[8], "yyyy-MM-dd");

            BorrowedBook* book = new BorrowedBook(name, publisher, author, ISBN, categroy, collectionLocation, currentCollection, allCollection, loanTime, nullptr);
            historyBooks.append(book);
        }
        file1.close();
    } else {
        qWarning() << "无法打开文件，错误信息：" << file1.errorString();
    }

    QFile file2(returnedBookFilePath);
    if (file2.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in2(&file2);
        in2.setCodec(codec);
        while (!in2.atEnd()) {
            QString line = in2.readLine();
            qDebug() << "已归还数据：" << line;
            line=line.replace(" ","");
            QStringList dataList = line.split("/");
            if (dataList.size() < 10) {
                qWarning() << "数据格式错误：" << line;
                continue;
            }

            QString name = dataList[0];
            QString publisher = dataList[1];
            QString author = dataList[2];
            QString ISBN = dataList[3];
            QString categroy = dataList[4];
            QString collectionLocation = dataList[5];
            int currentCollection = dataList[6].toInt();
            int allCollection = dataList[7].toInt();
            QDate loanTime = QDate::fromString(dataList[8], "yyyy-MM-dd");
            //QDate returnTime = QDate::fromString(dataList[9], "yyyy-MM-dd");
            qDebug()<<dataList;
            BorrowedBook* book = new BorrowedBook(name, publisher, author, ISBN, categroy, collectionLocation, currentCollection, allCollection, loanTime, nullptr);
            historyBooks.append(book);
        }
        file2.close();
    } else {
        qWarning() << "无法打开文件，错误信息：" << file2.errorString();
    }

    std::sort(historyBooks.begin(),historyBooks.end(),[](BorrowedBook *a, BorrowedBook *b) {
        return a->getLoanTime() > b->getLoanTime(); // 根据借阅时间排序
    });
}

void RecordBooks::setDataTotreeView(){
    QStandardItemModel *model = new QStandardItemModel(this);

    // 遍历借阅记录，按照月份分组
    for (const auto& record :historyBooks) {
        QString monthStr = record->getLoanTime().toString("yyyy-MM");
        qDebug()<<record->getLoanTime();
        QStandardItem *monthItem = nullptr;
        // 查找是否已存在对应月份的节点
        for (int i = 0; i < model->rowCount(); ++i) {
            QStandardItem *existingMonthItem = model->item(i, 0);
            if (existingMonthItem->text() == monthStr) {
                monthItem = existingMonthItem;
                break;
            }
        }
        if (!monthItem) {
            // 如果不存在对应月份节点，则创建新的月份节点
            monthItem = new QStandardItem(monthStr);
            model->appendRow(monthItem);
        }

        // 创建代表每条借阅记录的子节点
        QStandardItem *bookItem = new QStandardItem(QString("借阅书籍: 《%1》\n作者: %2\n借阅时间: %3")
                                                        .arg(record->getName())
                                                        .arg(record->getAuthor())
                                                        .arg(record->getLoanTime().toString("yyyy年MM月dd日")));
        monthItem->appendRow(bookItem);
    }
    // 设置QtreeView的数据模型
    ui->treeView->setModel(model);
    // 设置树形视图的展开模式，默认展开所有节点
    ui->treeView->expandAll();
    /*QModelIndex firstIndex = model->index(0, 0);
    ui->treeView->expand(firstIndex);*/
    ui->treeView->setHeaderHidden(true);
}

